package com.example.goodsmanagementcabinet.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.utils.PhoneUtils;
import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.Date;

public class Utils {
    public static String sDeviceMd5;

    private static final Date dateUtils = new Date();

    public static Date getInstance() {
        return dateUtils;
    }

    public static String getDeviceMd5() {
        if (sDeviceMd5 == null) {
            String imei = getIMEI();
            sDeviceMd5 = bytesToMD5(imei.getBytes());
        }
        return sDeviceMd5;
    }

    private static String getIMEI() {
        String imei = PhoneUtils.getPhoneIMEI(GoodBoxManagerApp_.getInstance());
        if (TextUtils.isEmpty(imei)) {
            imei = Build.SERIAL;
        }
        return imei;
    }

    //把字节数组转成16进位制数
    public static String bytesToHex(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        //把数组每一字节换成16进制连成md5字符串
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString();
    }

    //把字节数组转换成md5
    public static String bytesToMD5(byte[] input) {
        String md5str = null;
        try {
            //创建一个提供信息摘要算法的对象，初始化为md5算法对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //计算后获得字节数组
            byte[] buff = md.digest(input);
            //把数组每一字节换成16进制连成md5字符串
            md5str = bytesToHex(buff);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5str;
    }


    public static String getTime() {
//        Calendar c = Calendar.getInstance();
//        //  c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
//        String mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
//        String mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
//        String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
//        String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));  //星期
//        String mHour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));//时
//        String mMinute = String.valueOf(c.get(Calendar.MINUTE));//分
//        String mSecond = String.valueOf(c.get(Calendar.SECOND));//秒
//
//        if ("1".equals(mWay)) {
//            mWay = "天";
//        } else if ("2".equals(mWay)) {
//            mWay = "一";
//        } else if ("3".equals(mWay)) {
//            mWay = "二";
//        } else if ("4".equals(mWay)) {
//            mWay = "三";
//        } else if ("5".equals(mWay)) {
//            mWay = "四";
//        } else if ("6".equals(mWay)) {
//            mWay = "五";
//        } else if ("7".equals(mWay)) {
//            mWay = "六";
//        }
//        if (mMinute.length() == 1) {
//            mMinute = "0" + mMinute;
//        }
//
//        if (mSecond.length() == 1) {
//            mSecond = "0" + mSecond;
//        }
//    //    return mYear + "年" + mMonth + "月" + mDay + "日" + "  " + "星期" + mWay + "  " + mHour + ":" + mMinute + ":" + mSecond;
//        return mYear + "年" + mMonth + "月" + mDay + "日" + "  " + "星期" + mWay + "  " + mHour + ":" + mMinute;
        Date d = new Date();
        String result = d.toLocaleString();
        result = result.substring(0, result.lastIndexOf(":"));
        return result;
    }

    /**
     * 判断网络状态
     *
     * @return
     */
    public static boolean CheckNetWork() {
        ConnectivityManager connectivityManager = (ConnectivityManager) GoodBoxManagerApp_.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info == null || !info.isAvailable()) {
            return false;
        } else {
            return true;
        }
    }

    public static String getPid(String processName) {
        ActivityManager am = (ActivityManager) GoodBoxManagerApp_.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : am
                .getRunningAppProcesses()) {
            if (TextUtils.equals(processName, appProcess.processName)) {
                return appProcess.pid + "";
            }
        }
        return "";
    }


//    public static void hideVirtureKey() {
//        execCommand("mount -o rw,remount /system");
//        execCommand("mv system/priv-app/SystemUI.apk system/priv-app/bakSystemUI.apk");
//        String pid = getPid("com.android.systemui");
//        execCommand("kill -9 " + pid);
//    }
//
//    public static void showVirtureKey() {
//        try {
//            execCommand("mount -o rw,remount /system");
//            Thread.sleep(500);
//            execCommand("mv system/priv-app/bakSystemUI.apk system/priv-app/SystemUI.apk");
//            Thread.sleep(500);
//            Intent intent = new Intent();
//
//            intent.setComponent(new ComponentName("com.android.systemui",
//
//                    "com.android.systemui.SystemUIService"));
//
//
//            EscortApplication_.getInstance().startService(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    public static void execCommand(String command) {
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("su");// the phone must be root,it can exctue the adb command
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String setSex(String sex) {
        if (sex.equals("0")) {
            return "男";
        } else {
            return "女";
        }
    }


    public static int getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    public static int getCurrentMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH);
    }

    public static int getCurrentDays() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static void t(String msg) {
        boolean isMainThread = Thread.currentThread() == Looper.getMainLooper().getThread();
        if (!isMainThread) {
            Looper.prepare();
            Toast.makeText(GoodBoxManagerApp_.getInstance(), msg, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(GoodBoxManagerApp_.getInstance(), msg, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * encodeBase64File:(将文件转成base64 字符串). <br/>
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     * @author guhaizhou@126.com
     * @since JDK 1.6
     */
    public static String encodeBase64File(String path) {
        if (TextUtils.isEmpty(path)) return null;
        File file = null;
        FileInputStream inputFile = null;
        try {
            file = new File(path);
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return Base64.encodeToString(buffer, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputFile != null) {
                    inputFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * decoderBase64File:(将base64字符解码保存文件). <br/>
     *
     * @param base64Code 编码后的字串
     * @param savePath   文件保存路径
     * @throws Exception
     * @author guhaizhou@126.com
     * @since JDK 1.6
     */
    public static String decoderBase64File(String base64Code, String savePath) {
        //byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = null;
        try {
            File f = new File(savePath);
            if(f.exists()) {
                f.delete();
            }
            byte[] buffer = Base64.decode(base64Code, Base64.DEFAULT);
             out = new FileOutputStream(savePath);
            out.write(buffer);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return savePath;
    }

    public static Bitmap base64ToBitmap(String base64Data) {
        try {
            if (!TextUtils.isEmpty(base64Data)) {
                byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }

    public static Bitmap jpegFileToBitmap(String path) {
        byte[] buf = new byte[1024 * 1024];// 1M
        Bitmap bitmap = null;

        try {

            FileInputStream fis = new FileInputStream(path);
            int len = fis.read(buf, 0, buf.length);
            bitmap = BitmapFactory.decodeByteArray(buf, 0, len);
            if (bitmap == null) {
                System.out.println("len= " + len);
                System.err
                        .println("path: " + path + "  could not be decode!!!");
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

        return bitmap;


    }

    public static boolean isTopActivity(String actName) {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) GoodBoxManagerApp_.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(actName)) {
            isTop = true;
        }
        return isTop;
    }


    private static void setVirtualKey(View view) {
        //保持布局状态
        int uiOptions =
                //View.SYSTEM_UI_FLAG_LAYOUT_STABLE|
                //布局位于状态栏下方
                // View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION|
                //全屏
                //  View.SYSTEM_UI_FLAG_FULLSCREEN|
                //隐藏导航栏
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        //|
        // View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        if (Build.VERSION.SDK_INT >= 19) {
            uiOptions |= 0x00001000;
        } else {
            uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        view.setSystemUiVisibility(uiOptions);
    }

    public static void hideVirtualKey(View view) {
        final View v = view;
        setVirtualKey(v);
        View.OnSystemUiVisibilityChangeListener listener;
        if (v.getTag() == null) {
            listener = new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    setVirtualKey(v);
                }
            };
            v.setTag(listener);
        }

        v.setOnSystemUiVisibilityChangeListener((View.OnSystemUiVisibilityChangeListener) v.getTag());
    }


    public static void deleteFile(File file) {
        if (file.isFile()) {
            deleteFileSafely(file);
            return;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                deleteFileSafely(file);
                return;
            }
            for (int i = 0; i < childFiles.length; i++) {
                deleteFile(childFiles[i]);
            }
            deleteFileSafely(file);
        }
    }

    /**
     * 安全删除文件.
     *
     * @param file
     * @return
     */
    private static boolean deleteFileSafely(File file) {
        if (file != null) {
            String tmpPath = file.getParent() + File.separator + System.currentTimeMillis();
            File tmp = new File(tmpPath);
            file.renameTo(tmp);
            return tmp.delete();
        }
        return false;
    }
    public static void send(final String command, InetAddress ip) throws IOException {
        final DatagramPacket dp = new DatagramPacket(command.getBytes(), command.getBytes().length, ip, 8898);
        System.out.println(ip);
        final DatagramSocket ds = new DatagramSocket();
        new Thread() {
            public void run() {
                try {
                    ds.send(dp);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ds.close();
                System.out.println("发送成功:" + command);
                //abc = true;
            }
        }.start();
    }
}


